package com.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.example.common.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

// 第一种 流量控制异常处理方式。 适用于web接口
@Component
public class MyBlockException implements BlockExceptionHandler {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String resourceName, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = httpServletResponse.getWriter();
        R r = new R();
        r.setCode(500);
        r.setMsg(resourceName + ": 被sentinel限制了" + e.getClass());
        String json = objectMapper.writeValueAsString(r);
        printWriter.write(json);
        printWriter.flush();
        printWriter.close();
    }
}
